const express = require('express');
const router = express.Router();

// 设置相关API
function setupSettingsRoutes(db) {
    // 获取所有设置
    router.get('/', (req, res) => {
        db.all('SELECT * FROM settings', (err, rows) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            
            // 将设置转换为对象格式
            const settingsObj = {};
            rows.forEach(row => {
                try {
                    // 尝试解析JSON值
                    settingsObj[row.key] = JSON.parse(row.value);
                } catch (e) {
                    // 如果解析失败，使用原始字符串
                    settingsObj[row.key] = row.value;
                }
            });
            
            res.json(settingsObj);
        });
    });

    // 获取单个设置
    router.get('/:key', (req, res) => {
        const { key } = req.params;
        db.get('SELECT value FROM settings WHERE key = ?', [key], (err, row) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            if (!row) {
                return res.status(404).json({ error: '未找到该设置' });
            }
            
            try {
                // 尝试解析JSON值
                res.json(JSON.parse(row.value));
            } catch (e) {
                // 如果解析失败，返回原始字符串
                res.json(row.value);
            }
        });
    });

    // 更新设置
    router.put('/:key', (req, res) => {
        const { key } = req.params;
        let { value } = req.body;
        
        // 将值转换为字符串存储
        const valueStr = typeof value === 'object' ? JSON.stringify(value) : String(value);
        
        // 检查设置是否存在
        db.get('SELECT * FROM settings WHERE key = ?', [key], (err, row) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            
            const sql = row ? 
                'UPDATE settings SET value = ? WHERE key = ?' : 
                'INSERT INTO settings (key, value) VALUES (?, ?)';
            
            db.run(sql, [valueStr, key], function(err) {
                if (err) {
                    res.status(500).json({ error: err.message });
                    return;
                }
                res.json({ success: true });
            });
        });
    });

    // 批量更新设置
    router.post('/batch', (req, res) => {
        const settingsObj = req.body;
        if (typeof settingsObj !== 'object') {
            return res.status(400).json({ error: '请求体必须是设置对象' });
        }

        // 开始事务
        db.serialize(() => {
            db.run('BEGIN TRANSACTION');
            
            const stmt = db.prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)');
            
            let hasError = false;
            let errorMessage = '';
            
            Object.entries(settingsObj).forEach(([key, value]) => {
                if (!hasError) {
                    try {
                        const valueStr = typeof value === 'object' ? JSON.stringify(value) : String(value);
                        stmt.run(key, valueStr);
                    } catch (err) {
                        hasError = true;
                        errorMessage = err.message;
                    }
                }
            });
            
            stmt.finalize();
            
            if (hasError) {
                db.run('ROLLBACK');
                res.status(500).json({ error: errorMessage });
            } else {
                db.run('COMMIT');
                res.json({ success: true });
            }
        });
    });

    // 获取用户配置的完整设置对象（适配前端格式）
    router.get('/user/complete', (req, res) => {
        db.all('SELECT * FROM settings', (err, rows) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            
            // 将设置转换为前端期望的完整对象格式
            const settingsMap = {};
            rows.forEach(row => {
                try {
                    settingsMap[row.key] = JSON.parse(row.value);
                } catch (e) {
                    settingsMap[row.key] = row.value;
                }
            });
            
            // 构建完整的设置对象，确保包含前端需要的所有字段
            const completeSettings = {
                dailyReminder: {
                    enabled: settingsMap.daily_reminder_enabled === true || settingsMap.daily_reminder_enabled === 'true',
                    time: settingsMap.daily_reminder_time || '09:00'
                },
                newsSubscription: {
                    enabled: settingsMap.news_subscription_enabled === true || settingsMap.news_subscription_enabled === 'true',
                    categories: settingsMap.news_subscription_categories || ['models', 'tools', 'research'],
                    frequency: settingsMap.news_subscription_frequency || 'daily'
                },
                notification: {
                    lastDailyReminder: settingsMap.last_daily_reminder || new Date().toISOString(),
                    lastNewsPush: settingsMap.last_news_push || new Date().toISOString(),
                    lastTaskGenerationDate: settingsMap.last_task_generation_date || new Date().toISOString()
                }
            };
            
            // 添加任何其他单独存储的设置字段，确保前端能够获取到所有必要的设置
            // 这里可以根据需要添加更多字段的映射
            
            res.json(completeSettings);
        });
    });

    // 更新通知时间戳
    router.put('/notification/:type', (req, res) => {
        const { type } = req.params;
        const validTypes = ['daily_reminder', 'news_push', 'task_generation'];
        
        if (!validTypes.includes(type)) {
            return res.status(400).json({ 
                error: '无效的通知类型',
                validTypes 
            });
        }
        
        const timestamp = new Date().toISOString();
        const key = `last_${type}`;
        
        db.run('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)', 
            [key, timestamp], 
            function(err) {
                if (err) {
                    res.status(500).json({ error: err.message });
                    return;
                }
                res.json({ 
                    success: true,
                    key,
                    timestamp
                });
            }
        );
    });

    return router;
}

module.exports = setupSettingsRoutes;